package com.mvc.action;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.container.SpringContainer;
import com.mvc.utils.ActionForm;
import com.mvc.utils.FullForm;

public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8;pageEncoding=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String url = "";
		String path = request.getServletPath().split("\\.")[0];
		List<SpringContainer> list = (List<SpringContainer>)getServletContext().getAttribute("simple");
		for(SpringContainer springContainer : list){
			if(springContainer.getUrl().equals(path)){
				String formclass = springContainer.getEntityName();
				ActionForm form = FullForm.full(formclass, request);
				try {
					Class<?> clazz = Class.forName(springContainer.getClassName());
					Object o = clazz.newInstance();
					Method method = clazz.getMethod(springContainer.getMethodName(), Class.forName(springContainer.getEntityName()));
					url = (String)method.invoke(o, form);
				}catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
